from celery_tasks.image.tasks import send_image_code
from ihome.utils.views import LoginRequiredMixin

from django.views import View
from django.http import JsonResponse

from qiniuyun import qiniu_storage
from users.models import User


class LoginLogoutView(LoginRequiredMixin, View):
    def get(self, request):
        """只有登录用户才能进入该类视图"""
        # 个人中心

        user = User.objects.get(id=request.user.id)

        dict = {

            "mobile": user.mobile,
            "name": user.real_name,
            "user_id": user.id,
        }
        return JsonResponse({
            "data": dict,
            "errmsg": "OK",
            "errno": "0",

        })

class UpdateTitleAddressView(LoginRequiredMixin, View):

    def put(self, request):
        """获取用户名地址，修改用户名"""
        # 接收参数：地址用户名
        json_dict = json.loads(request.body.decode())
        name = json_dict.get('name')

        try:

            User.objects.filter(id=request.user.id).update(
                real_name=name
            )
        except Exception as e:
            return JsonResponse({'errno': 400,
                                 'errmsg': '用户名修改失败'})

        # 4.响应删除地址结果
        return JsonResponse({'errno': 0,

                             'errmsg': '修改成功'})
import re
import json


class RegisterView(LoginRequiredMixin, View):


    def get(self, request):
        user = request.user
        real_name = user.real_name
        id_card = user.id_card

        return JsonResponse({
            'errno': 0,
            'errmsg': "success",
            'data': {"real_name": real_name,
                     "id_card": id_card}
        })


    def post(self, request):
        '''接收参数, 保存到数据库'''
        # 1.接收参数
        dict = json.loads(request.body.decode())
        real_name = dict.get('real_name')
        id_card = dict.get('id_card')

        # 2.校验(整体)
        if not all([real_name, id_card]):
            return JsonResponse({'errno': 400,
                                 'errmsg': '缺少必传参数'})

        # 3.real_name检验
        if not re.match(r'^\w{2,5}$', real_name):
            return JsonResponse({'errno': 400,
                                 'errmsg': '真实姓名格式有误'})

        # 4.id_card检验
        if not re.match(r'^([1-9]\d{5}[12]\d{3}(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01])\d{3}[0-9xX])$', id_card):
            return JsonResponse({'errno': 400,
                                 'errmsg': '身份证格式有误'})

        # 保存到数据库 (real_name,id_card])
        try:
            user = User.objects.get(id=request.user.id)
            user.real_name = real_name,
            user.id_card = id_card
            user.save()

        except Exception as e:
            return JsonResponse({'errno': 400,
                                 'errmsg': '保存到数据库出错'})

        # 13.拼接json返回
        return JsonResponse({'errno': 0,
                             'errmsg': '认证信息保存成功'})

class UserImage(View):

    def post(self, request):

        rec_data = request.FILES.get('avatar')

        img_url = send_image_code(rec_data)

        try:
            user = request.user
            user.avatar= img_url
            user.save()
        except Exception:
            return JsonResponse({
                'errno': 4101,
                'errmsg': "头像上传失败"
            })


        return JsonResponse({
            'data': {
                'avatar_url': img_url
            },
            'errno': 0,
            'errmsg': "头像上传成功",
        })


